#!/usr/bin/env node
import { getChannelName, getUrls, getVideosUrl } from "./parser";
import { prompt } from "./output";
import { exec } from "child_process";
import { readFile, writeFile, stat } from "fs/promises";
import { join } from "path";
import { homedir } from "os";

const CHANNEL_FILE = join(homedir(), ".config/youtube/channels.txt");

async function main() {
  const urls = await getUrls();
  let channels: string[] = [];
  try {
    if (await stat(CHANNEL_FILE)) {
      const res = JSON.parse(
        await readFile(CHANNEL_FILE, {
          encoding: "utf8",
        })
      );

      channels = res;
    }
  } catch {
    const promises = urls.map((url) => getChannelName(url));
    channels = (await Promise.all(promises)) as string[];
    await writeFile(CHANNEL_FILE, JSON.stringify(channels));
  }

  try {
    const { index: channelIndex } = await prompt(channels as string[]);
    const videos = await getVideosUrl(urls[channelIndex]);

    if (!videos.length) {
      return console.log("I can't find videos. Please try later");
    }

    const videoTitles = videos.map((video) => video.title) as string[];

    const { index: videoIndex } = await prompt(videoTitles);

    exec(`mpv ${videos[videoIndex].videoUrl}`);
  } catch {
    console.log("You haven't chosen video or channel");
  }
}

main();
